//
//  RedPointButton.m
//  QA
//
//  Created by 李小龙 on 2017/6/15.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "RedPointButton.h"

@implementation RedPointButton

+ (instancetype)buttonWithType:(UIButtonType)buttonType {
    RedPointButton *button = [super buttonWithType:buttonType];
    return button;
}

- (UILabel *)redPoint {
    if (!_redPoint) {
        _redPoint = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
        [_redPoint setBackgroundColor:[UIColor redColor]];
        [_redPoint setFont:TextPingFangMediumFontSize(8)];
        [_redPoint setTextColor:[UIColor whiteColor]];
        [_redPoint setTextAlignment:NSTextAlignmentCenter];
        [_redPoint setHidden:YES];
        [_redPoint.layer setMasksToBounds:YES];
        [_redPoint setBackgroundColor:[UIColor redF2color]];
    }
    return _redPoint;
}

- (void)setRedPointText:(NSString *)text {
    if (!TextIsNotNil(text) || text.integerValue == 0) {
        [self.redPoint setHidden:YES];
        return;
    }
    
    [self.redPoint setHidden:NO];
    if (text.integerValue > 99) {
        text = @"99+";
    }
    [self.redPoint setText:text];
    [self.redPoint sizeToFit];
    [self.redPoint setHeight:10];
    
    if (self.redPoint.width <= 10) {
        [self.redPoint setWidth:10];
    } else {
        [self.redPoint setWidth:self.redPoint.width+5];
    }
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self addSubview:self.redPoint];
    [self bringSubviewToFront:self.redPoint];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if ((self.width - self.titleLabel.right) > self.redPoint.width) {
        self.redPoint.left = self.titleLabel.right;
    } else {
        self.redPoint.left = self.width - self.redPoint.width;
    }
    self.redPoint.bottom = self.titleLabel.top+5;
    [self.redPoint.layer setCornerRadius:self.redPoint.height/2.0];
}

@end
